/**
 * Created by Dalyn on 2017/2/28.
 */
import React from 'react';
import { Link, router } from 'react-router';
import Relay from "react-relay";
import EventManager from '../../util/EventManager'
import Confirm from '../../common/Confirm';
import {hashHistory} from 'react-router';
import TitleMessageMutation from './mutation/TitleMessageMutation';
import getMessageTotalMutation from './mutation/getMessageTotalMutation'

import classNames from 'classnames';
import {_message,_Icon} from 'ANT_DE';
const message = _message,
      Icon = _Icon;
import './css/Title.css';

import {RealClass} from 'fly';

export default class Head extends React.Component {

    // static defaultProps = {
    //     svgStyleLeft:"M31.580939,13.24425C31.580939,13.24425,8.419061,32.017897,8.419061,32.017897C8.419061,32.017897,31.580939,50.75575,31.580939,50.75575",
    //     svgStyleRight:"M34.419061,13.24425C34.419061,13.24425,57.580939,32.017897,57.580939,32.017897C57.580939,32.017897,34.419061,50.75575,34.419061,50.75575"
    // };

    constructor(props){
        super(props);
        this.state = {
          title_modal_visible: false,
          pageNum: '1',
          messageData: [],
          totalResult: '',
          enId: sessionStorage.getItem('enterpriseId'),
          isLoading:true,
          svgStyle:true
        };

        this.username = sessionStorage.getItem('username');
        this.enterpriseName = sessionStorage.getItem('enterpriseName');

        this.titleClick = this.titleClick.bind(this);
    }

    //页面渲染之前
    componentWillMount(){
      //获取未读消息数量
      Relay.Store.commitUpdate(
          new getMessageTotalMutation({
            enId: this.state.enId,
            pageNum: this.state.pageNum,
            pageSize: '12',
            msgStatus: '0'
          }),
          {
              onFailure: () => {
                  message.error("请求失败");
              },
              onSuccess: (response) => {
                let errorCode = response.queryMessagesByCompanyId.queryMessagesByCompanyId.errorCode

                if (errorCode == 0) {
                  let totalResult = response.queryMessagesByCompanyId.queryMessagesByCompanyId.totalResult
                  if(totalResult) {
                    this.setState({
                      totalResult: totalResult
                    })
                  }
                } else {
                  // alert('未读消息请求失败')
                }
              }
          }
      );
    }

    //更新阶段
    componentWillReceiveProps() {
      this.setState({
        title_modal_visible: false
      })
    }

    componentDidMount(){
      this.documentClickHandler=(e)=> {
        this.setState({
          title_modal_visible: false
        })
      }
      document.addEventListener('click', this.documentClickHandler)
    }

    //用户退出按钮
    quit(){
        // document.cookie= "token="+null;
        sessionStorage.setItem('token','');
        sessionStorage.setItem('serviceType','');
        sessionStorage.setItem('enterpriseId','');
        sessionStorage.setItem('permissionId','');
        sessionStorage.setItem('entype','');
        sessionStorage.setItem('enterpriseName','');
        sessionStorage.setItem('address','');
        sessionStorage.setItem('uid','');
        sessionStorage.setItem('username','');
        sessionStorage.setItem('phone','');
        sessionStorage.setItem('uid','');

        hashHistory.push('/');
        EventManager.emitter('islogin',false);
    }

    //个人中心a
    mycenter(){
        hashHistory.push('/mycenter');
    }

    queryClickEle(ele,parents){
        let curEle = ele;

        while (true){
            if(curEle.nodeName === "BODY" || curEle == null){ return false;  }

            if(curEle.parentElement == parents || curEle == parents){
                return true;
            }else{
                curEle = curEle.parentElement
            }
        }
    }

    //title上消息点击时弹框出现获取弹框内容
    messageClick (e) {
        const ele = document.getElementsByClassName("title_order_modal")[0],

            ele1 = document.getElementsByClassName("title_ico2")[0];



        e.nativeEvent.stopImmediatePropagation();

        if (this.state.title_modal_visible  &&　!this.queryClickEle(e.target,ele) ) {
            this.setState({ title_modal_visible: false,isLoading:false})
        }

        if(e.target == ele1 || e.target == ele1.parentElement){
            if(this.state.title_modal_visible){ this.setState({title_modal_visible: false,isLoading:false}); return; }
            this.setState({title_modal_visible: true, isLoading:true});
            Relay.Store.commitUpdate(
                new TitleMessageMutation({
                    enId: this.state.enId,
                }),
                {
                    onFailure: () => {
                        message.error("请求失败")
                    },
                    onSuccess: (response) => {
                        let messageAll = response.queryMessagesForSix.queryMessagesForSix.messageAll
                        this.setState({
                            messageData:messageAll ,
                            isLoading:false
                        })
                    }
                }
            );
        }
    }

    messagesModal(e) {
      e.nativeEvent.stopImmediatePropagation();
    }

    messageListClick(){

      hashHistory.push('/MessageList');

    }

    titleClick = ()=>{
        let b = document.body;
        let cls = new RealClass(),c = "nav_hidden";

        if(cls.hasClass(b,c)){
            cls.removeClass(b,c);
        }else{
            cls.addClass(b,c);
        }

        this.setState({svgStyle:!this.state.svgStyle})
    };

    render() {
        const props = Object.assign({},this.props);
        const {svgStyle} = this.state;

        const svg_g = svgStyle ? props.svgStyleLeft : props.svgStyleRight;

        return (
            <div className="titleBox clear">

                <div className="leftIcon" onClick={this.titleClick}>
                        <Icon type="bars"/>
                </div>

                <div className="title_enname">{this.enterpriseName}</div>

                <div className="rightBox" style={{display:'inlineBlock'}}>
                  <ul>
                    <Link to="/SuggestList"><li><i className="title_ico1"></i>意见反馈</li></Link>
                    <li onClick={this.messageClick.bind(this)} data-tag="title_message--tag_ly" style={{position: 'relative'}}>
                      <i className="title_ico2" data-tag="title_message--tag_ly"></i>消息
                      {
                        this.state.totalResult > 0 ? <b className="msgStatusTotal"><i>{this.state.totalResult > 99 ? '99+' : this.state.totalResult}</i></b> : null
                      }
                      <div className={classNames({"title_order_modal":true,"_open": this.state.title_modal_visible})}
                           onClick={this.messagesModal.bind(this)}>
                         <p>东方制衣有限公司</p>
                         <ol>
                             {
                                 this.state.isLoading ?  <div className="title_order_loading---con"> <Icon type="loading" /> </div> :
                                     this.state.messageData.length !==0 ? (this.state.messageData.map((v, i)=>{
                                         if (i < 5) {
                                            return <li onClick={this.messageListClick.bind(this)}>{v.msgDetails || v.yiDetail || v.jiaDetail}</li>
                                         }
                                     })) : <div className="title_order_empty--con"> 当前没有内容 </div>
                             }
                         </ol>
                         <h6><Link to="/MessageList"><a>更多</a></Link></h6>
                     </div>
                    </li>
                    <li className="title_linenone" onClick={this.mycenter.bind(this)}><i className="title_ico3"></i>{this.username}</li>
                  </ul>
                  <p className="quit" onClick={this.quit.bind(this)}><i className="quit_ico"></i>退出</p>
                </div>
            </div>
        )
    }
}
